import bcrypt
from flask_sqlalchemy import SQLAlchemy

#数据库对象
db = SQLAlchemy()

#定义User Model
class User(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    #unique=True保证用户名唯一
    username=db.Column(db.String(20),unique=True,nullable=False)
    password_hash=db.Column(db.String(255),nullable=False)

#密码进行hash加密
    def set_password(password):
    # 生成盐
        salt = bcrypt.gensalt()
        return bcrypt.hashpw(password.encode('utf-8'), salt).decode('utf-8')

    #登录时验证密码是否一致
    def check_password(self, password):
        return bcrypt.checkpw(password.encode('utf-8'), self.password_hash.encode('utf-8'))
    def to_dict(self):
        return {
            'id': self.id,
            'username': self.username
        }

#定义好友model
class Friend(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    user_id=db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False)
    friend_id=db.Column(db.Integer,db.ForeignKey('user.id'),nullable=False)
    remark = db.Column(db.String(255), nullable=False)

    def to_dict(self):
        return {
            'id': self.id,
            'user_id': self.user_id,
            'friend_id': self.friend_id,
            'remark': self.remark
        }